<?php

/**
 * Created by PhpStorm.
 * User: Evan
 * Date: 16/3/10
 * Time: 下午5:21
 */
class Keyword extends MY_Agent_Controller
{
    public function index()
    {
        $limit   = 20;
        $page    = (int)$this->uri->segment(3, 0);
        $offset  = ($page < 1) ? 0 : ($page - 1) * $limit;
        $keyword = trim($this->input->get_post('keyword'));
        $param   = '';
        $where   = array();


        if (!empty ($keyword))
        {
            $param = '?keyword='.$keyword;
            $where['keyword like'] = '%'.$keyword.'%';
        }


        $this->load->model('Model_keyword', 'keyword');
        $list  = $this->keyword->lists($offset, $limit, $where);
        $count = $this->keyword->count($where);


        $this->load->library('pagination');
        $pageConfig = $this->page_config(url('admin').'/Keyword/index'.$param, $count, $limit);
        $this->pagination->initialize($pageConfig);
        $pageHtml = $this->pagination->create_links();


        $data = array(
            'title'     => '搜索关键字列表',
            'list'      => $list,
            'page_html' => $pageHtml,
            'keyword'   => $keyword,
        );
        $this->load->view('agent/keyword/index', $data);
    }


    public function create()
    {
        $kid = (int)$this->uri->segment(3);

        $data = array(
            'title' => '编辑搜索关键字',
        );

        if ($kid)
        {
            $this->load->model('Model_keyword', 'keyword');
            $data['data'] = $this->keyword->getById($kid);
        }


        $this->load->view('agent/keyword/create', $data);
    }


    public function save()
    {
        $keyword = trim($this->input->get_post('keyword'));
        $link    = trim($this->input->get_post('link'));
        $sort    = (int)$this->input->get_post('sort');
        $kid     = (int)$this->input->get_post('kid');

        $data = array(
            'keyword' => $keyword,
            'link'    => $link,
            'sort'    => $sort,
        );

        $this->load->model('Model_keyword', 'keyword');

        $this->keyword->save($data, $kid);

        $this->load->helper('url');
        redirect(url('admin').'Keyword/index');
    }


    public function delete()
    {
        $response = array('code' => '0', 'msg' => '删除成功');


        do {
            $kid =  $this->input->get_post('kid');


            if (empty ($kid))
            {
                $response = error(100000);//参数不全
                break;
            }

            $this->load->model('Model_keyword', 'keyword');

            $res = $this->keyword->delete(array('kid' => $kid));
            if (!$res)
            {
                $response = error(100001);//参数不全
                break;
            }
        } while (false);

        $this->$this->json_output($response);
    }
}